package vn.cuhanh;

import java.io.File;

import com.actionbarsherlock.app.ActionBar;

import vn.cuhanh.sys.Downloader;
import vn.cuhanh.utils.HelperFunc;
import vn.cuhanh.utils.ViewHelper;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TextView;

public class UpdateActivity extends Activity {
	
	private boolean downloading = false; 
	private ProgressBar progressBar;
	private TextView txtStatus;
	private String url;
	private Downloader downloader;
	private String savePath;
	private View loadingScreen;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		setTitle(R.layout.simple_title_bar);
//		boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		
		setContentView(R.layout.update_activity);
//		if(customTitleSupported) {
//			getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.simple_title_bar);
//		}
		
		progressBar = (ProgressBar)findViewById(R.id.progressBar);
		txtStatus = (TextView)findViewById(R.id.update_activity_status);
		
		url = getIntent().getExtras().getString("vn.cuhanh.UpdateActivity.url");
		if(url == null) {
			onBackPressed();
			return;
		}
		loadingScreen = findViewById(R.id.loading);
		
		String fileName = url.replaceAll("[^a-zA-Z 0-9]+", "");
		savePath = getResources().getString(R.string.update_apk_folder) + File.separator + fileName;
		File SDCardRoot = Environment.getExternalStorageDirectory();
		File file = new File(SDCardRoot, savePath);
		if(file.exists()) {
			install();
		} else {
			startDownloading();
		}
	}
	
	@Override
	public void onResume() {
		super.onResume();
		ViewHelper.initLoadingFrame(this, loadingScreen);
	}
	
	public void install() {
		try {
			if(savePath == null || savePath.isEmpty()) {
				return;
			}
			File SDCardRoot = Environment.getExternalStorageDirectory();
			File file = new File(SDCardRoot, savePath);
			if(!file.exists()) {
				return;
			}
			txtStatus.setText(R.string.installing);
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.fromFile(file),
					"application/vnd.android.package-archive");
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		} catch (Exception e) {
			// TODO: handle exception
			HelperFunc.readStackTrace(e);
		}
	}
	
	public void startDownloading() {
		downloader = new Downloader(this, url, savePath, progressBar, 
			new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					downloading = false;
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							install();
						}
					});
				}
			}, new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					downloading = false;
					txtStatus.setText(R.string.download_fail_message);
				}
			});
		txtStatus.setText(R.string.downloading);
		downloader.start();
		downloading = true;
	}
	
	@Override
	public void onBackPressed() {
		if(downloading) {
			confirmStopDownloadingAndQuit();
			return;
		}
		super.onBackPressed();
	}
	
	public void confirmStopDownloadingAndQuit() {
		if(!downloading) {
			return;
		}
		HelperFunc.showSimpleAlertDialog(this, null, getResources().getString(R.string.confirm_stop_downloading_message), 
				getResources().getString(R.string.confirm_stop_downloading_continue), 
				null, 
				getResources().getString(R.string.btn_exit_title), 
				new DialogInterface.OnClickListener(){

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						//stop download
						if(downloader != null) {
							downloader.stop();
						}
						//set flag
						downloading = false;
						onBackPressed();
					}
				}, 
				false);
	}
	
	public void showTitleBar() {
//		ActionBar actionBar = getSupportActionBar();
//		actionBar.setDisplayShowTitleEnabled(false);
//		View cView = getLayoutInflater().inflate(R.layout.title_bar, null);
//		actionBar.setDisplayUseLogoEnabled(false);
//		actionBar.setCustomView(cView);
//		actionBar.setDisplayShowCustomEnabled(true);
//		actionBar.setDisplayShowHomeEnabled(false);
	}
}
